package com.realgodo.site.service.communication;

import java.util.Date;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.realgodo.site.entity.application.Application;
import com.realgodo.site.entity.application.communication.Commentary;
import com.realgodo.site.service.application.ApplicationManager;

@Service
@Transactional
public class CommentaryManager extends CommunicationManager<Commentary> {
	
	public Page<Commentary> find(int pageSize,Map<String,Object> param){
		Page<Commentary> page=new Page<Commentary>(pageSize);
		Criteria c = sessionFactory.getCurrentSession().createCriteria(Commentary.class);
		if(param==null){
			page.setPageNo(1);
			return this.entityDao.findByCriteria(page, c);
		}
		page.setPageNo(super.isParamNotNull(param, Page.PAGE)?Integer.valueOf((String)getParamValue(param,  Page.PAGE)):1);//查询页数
		c.add(Restrictions.eq("application.id",(Long)getParamValue(param, "applicationId")));
		c.addOrder(Order.desc("id"));
		c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return this.entityDao.findByCriteria(page, c);
	}

	
	/**发布/更新评论*/
	public Commentary saveCommentary(Commentary commentary){
		if(commentary==null){
			return null;
		}
		String content=commentary.getContent();
		if(commentary.getId()!=null&&!Long.valueOf(-1).equals(commentary.getId())){
			commentary=this.get(commentary.getId());
		}else{
			Application application=(Application)sessionFactory.getCurrentSession().get(Application.class, commentary.getApplication().getId());
			application.setCommentaries(application.getCommentaries()+1);
			sessionFactory.getCurrentSession().save(application);
			commentary.setApplication(application);
			commentary.setPubTime(new Date());
		}
		commentary.setContent(ApplicationManager.convert(content));
		this.save(commentary);
		return commentary;
	}
}
